package net.shizhibao.www.mylibrary.view;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.AttributeSet;
import android.util.Log;

import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import net.shizhibao.www.mylibrary.utils.Contacts;


public class X5WebView extends WebView {
    /**
     * 自定义的，当js调用history.go时加载的链接，以监听history.go方法的调用
     */
    private WebViewClient client = new WebViewClient() {
        @Override
        public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
            super.onPageStarted(webView, s, bitmap);
        }

        @Override
        public void onPageFinished(WebView webView, String s) {
            super.onPageFinished(webView, s);
            String title = webView.getTitle();
            titleChange(title);
            if (onPageListener != null) {
                onPageListener.onPageFinish();
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.e(TAG, "shouldOverrideUrlLoading: " + url);
            if (url == null) return false;

            try {
                if (!url.startsWith("http") && !url.startsWith("https")) {
                    //打开对应app
                    goOtherApp(url);
                    return true;
                }
            } catch (Exception e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                return true;//没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
            sslErrorHandler.proceed();
        }
    };

    public void titleChange(String title) {
        if (onPageListener != null) {
            onPageListener.onTitleChange(title);
        }
    }

    private static final String TAG = "X5WebView";

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if (mOnScrollChangeListener != null) {
            if (t == 0) {
                mOnScrollChangeListener.canRefresh(true);
            } else {
                mOnScrollChangeListener.canRefresh(false);
            }
            // webview的高度
            float webcontent = getContentHeight() * getScale();
            // 当前webview的高度
            float webnow = getHeight() + getScrollY();
            mOnScrollChangeListener.onScrollChanged(l, t, oldl, oldt);
            if (Math.abs(webcontent - webnow) < 1) {
                //处于底端
                mOnScrollChangeListener.onPageEnd(l, t, oldl, oldt);
            } else if (getScrollY() == 0) {
                //处于顶端
                mOnScrollChangeListener.onPageTop(l, t, oldl, oldt);
            }
        }

    }

    private OnScrollChangeListener mOnScrollChangeListener;

    public void setmOnScrollChangeListener(OnScrollChangeListener mOnScrollChangeListener) {
        this.mOnScrollChangeListener = mOnScrollChangeListener;
    }

    public interface OnScrollChangeListener {

        public void onPageEnd(int l, int t, int oldl, int oldt);

        public void onPageTop(int l, int t, int oldl, int oldt);

        public void onScrollChanged(int l, int t, int oldl, int oldt);

        public void canRefresh(boolean b);

    }

    private void goOtherApp(final String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        getContext().startActivity(intent);

    }

    private void downloadListener() {
        this.setDownloadListener(new com.tencent.smtt.sdk.DownloadListener() {
            @Override
            public void onDownloadStart(String url, String s1, String s2, String s3, long l) {
                downloadByBrowser(url, true);
            }
        });

    }

    public void downloadByBrowser(String url) {
        downloadByBrowser(url, false);

    }

    public void downloadByBrowser(final String url, boolean isDown) {

        if (Contacts.office(url)) {
            if (isOfficeListener != null) {
                isOfficeListener.isOffice(url, isDown);
            } else {
                downloadByBrowser2(url, isDown);
            }
        } else {
            downloadByBrowser2(url, isDown);
        }

    }

    public void downloadByBrowser2(final String url, boolean isDown) {
        String str = "请求打开第三方app";
        if (isDown) {
            str = "请求下载";
        }
        new AlertDialog.Builder(getContext()).
                setMessage(str).
                setNegativeButton("取消", null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.addCategory(Intent.CATEGORY_BROWSABLE);
                            intent.setData(Uri.parse(url));
                            getContext().startActivity(intent);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).show();
    }

    @SuppressLint("SetJavaScriptEnabled")
    public X5WebView(Context arg0, AttributeSet arg1) {
        super(arg0, arg1);
        this.setWebViewClient(client);
        // this.setWebChromeClient(chromeClient);
        // WebStorage webStorage = WebStorage.getInstance();
        initWebViewSettings();

        this.getView().setClickable(true);
    }


    private void initWebViewSettings() {
        WebSettings webSetting = this.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setCacheMode(WebSettings.LOAD_DEFAULT);

        downloadListener();
    }

    public X5WebView(Context arg0) {
        super(arg0);
    }

    OnPageListener onPageListener;

    public void setOnPageListener(OnPageListener onPageListener) {
        this.onPageListener = onPageListener;
    }


    IsOfficeListener isOfficeListener;

    public void setIsOfficeListener(IsOfficeListener isOfficeListener) {
        this.isOfficeListener = isOfficeListener;
    }

    public interface IsOfficeListener {
        void isOffice(String url, boolean isDown);
    }

    public interface OnPageListener {
        void onPageFinish();

        void onTitleChange(String title);
    }
}
